<template>
	<view>
		<view :class="{'text-theme': hasChoose}">
			<button type="primary" class="topfixed-active" style="background-color: #007aff;" @click="toggle('center')" >筛选</button>
		</view>
		<!-- <button class="button topfixed-active" type="primary" style="background-color: #007aff;" @click="toggle('center')">筛选</button> -->
		<uni-popup ref="popup" background-color="#fff" @change="change" style="width: 50%;">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<uni-forms labelAlign="right" :modelValue="filterValue">
					<uni-forms-item  label="团队:" name="teamId">
						<uni-data-picker 
						placeholder="请选择团队" 
						:localdata="team" 
						@change="getProjectsByCondition"
						v-model="filterValue.teamId" />
					</uni-forms-item>
					<uni-forms-item  label="项目:" required name="projectId">
						<uni-data-picker 
						placeholder="请选择项目" 
						:localdata="project" 
						@change="getEmployee"
						v-model="filterValue.projectId" />
					</uni-forms-item>
					<uni-forms-item label="人员:" required name="worker">
						<uni-data-checkbox 
						mode="button" 
						multiple 
						v-model="filterValue.employee" 
						:localdata="worker">
						</uni-data-checkbox>
					</uni-forms-item>
					<uni-forms-item v-if="detailOrTotal == 'DETAIL'" label="方式:" required name="addMinus">
						<uni-data-picker 
						placeholder="发放/扣减" 
						:localdata="addMinus" 
						v-model="filterValue.addMinus" />
					</uni-forms-item>
					<uni-forms-item v-if="detailOrTotal == 'DETAIL'" label="方式:" required name="addMinus">
						<uni-data-picker 
						placeholder="发放方式" 
						:localdata="payment" 
						v-model="filterValue.payment" />
					</uni-forms-item>
					<uni-forms-item label="日期:" name="daterange">
						<uni-datetime-picker 
						v-model="dateRange" 
						type="datetimerange" 
						@change="changeTime"
						rangeSeparator="至" />
					</uni-forms-item>
					<button type="primary" style="background-color: #007aff;" @click="getSalary">查询</button>
				</uni-forms>
			</view>
		</uni-popup>
		<view class="page-content">
			<view class="data-chechbox-box">
				<uni-forms ref="baseForm">
					<uni-forms-item label="查询方式:" name="type">
						<uni-data-checkbox v-model="detailOrTotal" :localdata="detailOrTotals" @change="getSalary" />
					</uni-forms-item>
				</uni-forms>
			</view>
			<zb-table
			v-if="detailOrTotal == 'TOTAL'"
			:show-header="true"
			:columns="total_headers"
			:stripe="true"
			:fit="false"
			:highlight="true"
			show-summary
			sum-text="合计"
			:border="true"
			@rowClick="showDetail"
			:data="tableData"></zb-table>
			<uni-pagination
			v-if="detailOrTotal == 'DETAIL'"
			:total="total"
			:current="filterValue.currentPage"
			:pageSize="filterValue.pageSize"
			@change="changePage"
			title="顶部翻页" />
			<zb-table
			v-if="detailOrTotal == 'DETAIL'"
			:show-header="true"
			:columns="detail_headers"
			:stripe="true"
			:fit="false"
			:highlight="true"
			show-summary
			sum-text="合计"
			@rowClick="show"
			@edit="edit"
			:border="true"
			:data="tableData"></zb-table>
			<uni-pagination 
			v-if="detailOrTotal == 'DETAIL'"
			:current="filterValue.currentPage" 
			:pageSize="filterValue.pageSize"
			:total="total" 
			title="底部翻页" 
			@change="changePage" />
			<view class="btn-view" v-if="detailOrTotal == 'DETAIL'">
				<view>
					<text class="example-info">当前页：{{ filterValue.currentPage }}，数据总量：{{ total }}条，每页数据：{{ filterValue.pageSize }}</text>
				</view>
			</view>
		</view>
		<view>
			<xy-dialog style="width: 100%;"
			:title="isEdit == true ? '修改记录' : '详情'" 
			:show.sync="showDialog"
			:isShowCancel="isEdit"
			@cancelButton="clickCancel()" 
			@confirmButton="submit()">
				<view style="padding: 0 30upx 30upx;" v-if="isEdit == true">
					<uni-forms style="width: 95%; margin: 10rpx auto;"
					ref="baseForm" 
					:rules="rules" 
					labelAlign="right" 
					labelWidth="80"
					:modelValue="salaryData">
						<uni-forms-item  label="团队:" name="teamId">
							<uni-data-picker 
							placeholder="请选择团队" 
							:localdata="team" 
							@change="getProjectsByCondition"
							v-model="salaryData.teamId" />
						</uni-forms-item>
						<uni-forms-item label="项目:" required name="project">
							<uni-data-picker
							placeholder="请选择工程" 
							:localdata="project" 
							@change="getEmployee"
							v-model="salaryData.projectId" />
						</uni-forms-item>
						<uni-forms-item label="员工:" required name="employee">
							<uni-data-checkbox 
							mode="button" 
							v-model="salaryData.employeeId" 
							:localdata="worker">
							</uni-data-checkbox>
						</uni-forms-item>
						<uni-forms-item label="发放/扣减:" required name="addMinus">
							<uni-data-picker
							placeholder="请选择付款方式" 
							:localdata="addMinus" 
							v-model="salaryData.addMinus" />
						</uni-forms-item>
						<uni-forms-item label="金额:" required name="pay">
							<uni-easyinput type="text" v-model="salaryData.pay" placeholder="0.00" />
						</uni-forms-item>
						<uni-forms-item label="付款方式:" required name="payment">
							<uni-data-picker
							placeholder="请选择付款方式" 
							:localdata="payment" 
							v-model="salaryData.payment" />
						</uni-forms-item>
						<uni-forms-item label="备注:">
							<uni-easyinput type="textarea" v-model="salaryData.note" placeholder="请输入备注" />
						</uni-forms-item>
					</uni-forms>
				</view>
				<uni-list style="width:95%" v-if="isEdit == false">
					<uni-list-item 
					style="padding-left: 20px;"
					:title="salaryDetail.employee.realName == null || salaryDetail.employee.realName == '' ? salaryDetail.employee.nickName : salaryDetail.employee.realName"
					:thumb="salaryDetail.employee.avatar"
					thumbSize="lg"
					:note="salaryDetail.employee.phone == null ? '' : salaryDetail.employee.phone" />
					<uni-list-item>
						<template v-slot:header><view class="slot-title"><text>所属团队</text></view></template>
						<template v-slot:footer><view class="slot-text"><text>{{ salaryDetail.team.name }}</text></view></template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:header><view class="slot-title"><text>所属项目</text></view></template>
						<template v-slot:footer><view class="slot-text"><text>{{ salaryDetail.projectName }}</text></view></template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:header><view class="slot-title"><text>金额</text></view></template>
						<template v-slot:footer><view class="slot-text"><text>{{ salaryDetail.pay }}元</text></view></template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:header><view class="slot-title"><text>发放/扣减</text></view></template>
						<template v-slot:footer><view class="slot-text"><text>{{ salaryDetail.addMinusCN }}</text></view></template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:header><view class="slot-title"><text>发放方式</text></view></template>
						<template v-slot:footer><view class="slot-text"><text>{{ salaryDetail.paymentCN }}</text></view></template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:header><view class="slot-title"><text>发放时间</text></view></template>
						<template v-slot:footer><view class="slot-text"><text>{{ salaryDetail.payTime }}</text></view></template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:header><view class="slot-title"><text>备注</text></view></template>
						<template v-slot:footer><view class="slot-text"><text>{{ salaryDetail.note }}</text></view></template>
					</uni-list-item>
				</uni-list>
			</xy-dialog>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				total: 0,
				showDialog: false,
				isEdit: false,
				team: [],
				project: [],
				worker: [],
				dateRange: [],
				themeColor:"#007aff",
				titleColor: "#007aff",
				detailOrTotal: 'DETAIL',
				detailOrTotals: [{
					text: '工资发放记录',
					value: 'DETAIL'
				},{
					text: '工资统计',
					value: 'TOTAL'
				}],
				filterValue: {
					teamId: '',
					projectId: '',
					employee: [],
					startDate: '',
					endDate: '',
					addMinus: 'ADD',
					payment: 'CASH',
					currentPage: 1,
					pageSize: 15,
				},
				salaryData: {
					id: '',
					teamId: '',
					projectId: '',
					employeeId: '',
					pay: 0,
					addMinus: 'ADD',
					payment: 'CASH',
					note: '无',
				},
				salaryDetail: {
					id: '',
					team: {},
					projectName: '',
					pay: 0,
					employee: {},
					addMinus: 'ADD',
					addMinusCN: '发放',
					payment: 'CASH',
					paymentCN: '现金',
					payTime: '',
					note: '无',
				},
				addMinus: [
					{
						text: '所有',
						value: null
					},
					{
						text:'发放',
						value: 'ADD'
					},
					{
						text:'扣减',
						value: 'MINUS'
					},
				],
				rules: {
					project: {
						rules: [{
							required: true,
							errorMessage: '请选择工程'
						}]
					},
					pay: {
						rules: [{
							required: true,
							errorMessage: '请输入发放金额'
						}]
					},
					payment: {
						rules: [{
							required: true,
							errorMessage: '请选择付款方式'
						}]
					},
					employee: {
						rules: [{
							required: true,
							errorMessage: '请选择员工'
						}]
					},
					addMinus: {
						rules: [{
							required: true,
							errorMessage: '请选择发放还是扣减'
						}]
					}
				},
				total_headers: [
					{ name: 'projectName', label: '项目',fixed:false,width:100,emptyString:'--',fixed:true},
					{ name: 'employeeName', label: '员工',fixed:false,width:80,emptyString:'--',fixed:true},
					{ name: 'salary', label: '薪资/天',fixed:false,emptyString:'0',sorter:true},
					{ 
						name: 'days', 
						label: '工作时长(天)',
						fixed:false,
						emptyString:'0',
						sorter:true
					},
					{
						name: 'extWorkHours', 
						label: '加班时长(小时)',
						fixed:false,
						emptyString:'0',
						sorter:true
					},
					{
						name: 'errandDays', 
						label: '出差时长(天)',
						fixed:false,
						emptyString:'0',
						sorter:true
					},
					{
						name: 'baseTotalSalary',
						label: '基本工资(不含出差)',
						fixed:false,
						emptyString:'0',
						sorter:true,
					},
					{
						name: 'extTotalSalary',
						label: '加班工资',
						fixed:false,
						emptyString:'0',
						sorter:true,
					},
					{
						name: 'errandTotalSalary',
						label: '出差工资',
						fixed:false,
						emptyString:'0',
						sorter:true,
					},
					{
						name: 'errandExtendTotalSalary',
						label: '出差补助',
						fixed:false,
						emptyString:'0',
						sorter:true,
					},
					{ 
						name: 'totalSalary',
						label: '工资总额',
						fixed:false,
						emptyString:'0',
						sorter:true,
					},
					{ name: 'minusSalary', label: '应扣工资',fixed:false,emptyString:'0'},
					{ name: 'realSalary', label: '应发工资',fixed:false,emptyString:'0'},
					{ name: 'paySalary', label: '已发工资',fixed:false,emptyString:'0'},
					{ name: 'leftSalary', label: '剩余工资',fixed:false,emptyString:'0'},
				],
				fontSize: [25,20],
				detail_headers: [
					{ name: 'projectName', label: '项目',fixed:false,width:100,emptyString:'--',fixed:true},
					{ name: 'employeeName', label: '员工',fixed:false,width:80,emptyString:'--',fixed:true},
					{ name: 'pay', label: '金额',fixed:false,emptyString:'0'},
					{ 
						name: 'addMinus', 
						label: '发放/扣减',
						fixed:false,
						emptyString:'--',
						filters: {
							'ADD': '发放',
							'MINUS': '扣减'
						}
					},
					{ 
						name: 'payment',
						label: '发放方式',
						fixed:false,
						filters:{
							'CASH':'现金',
							'WEIXIN':'微信',
							'ZFB': '支付宝',
							'BANK': '银行卡'
							
						},
						emptyString:'--'},
					{ name: 'payTime', label: '日期', width:160, fixed:false,emptyString:'--',sorter:true},
					{ 
						name: 'operation', 
						type:'operation',
						label: '操作',
						renders:[
							{
								name:'编辑',
								type: 'primary',
								size: 'mini',
								func:'edit' // func 代表子元素点击的事件 父元素接收的事件 父元素 @edit
							},
						],
					},
				],
				tableData: [],
				payment: [
					{
						text: '所有',
						value: null
					},
					{
						text:'现金',
						value: 'CASH'
					},
					{
						text:'微信',
						value: 'WEIXIN'
					},
					{
						text:'支付宝',
						value: 'ZFB'
					},
					{
						text:'银行卡',
						value: 'BANK'
					},
				],
			}
		},
		onLoad() {
			this.getTeam();
			this.getProjectsByCondition();
			this.getEmployee();
			this.getSalary();
		},
		onReady() {
			// 需要在onReady中设置规则
		// 	this.$refs.addForm.setRules(this.rules)
		},
		onShow() {
			if(!this.$dry.isLogin()) {
				uni.showModal({
					title: "信息",
					content: "需要登录后查看，去登录",
					showCancel: false,
					confirmText: "确定",
					success: function (res) {
						if (res.confirm) {
							uni.switchTab({
								url: '../user/user',
							})
						}
					}
				});
			}
		},
		computed: {
			// newProject() {
			// 	return this.addSalary.dry_project;
			// }
		},
		watch: {
			isEdit(val){
				if(val === true) {
					this.$nextTick(() => {
						this.$refs.baseForm.setRules(this.rules);
					})
				}
			}
		},
		onShareAppMessage(res) {
		    if (res.from === 'button') {// 来自页面内分享按钮
		      console.log(res.target)
		    }
		    return {
		      title: '大家都在用这款小工具管理项目，快来试试吧！！！',
		      path: '/pages/index/index'
		    }
		},
		methods: {
			change(e) {
				console.log('当前模式：' + e.type + ',状态：' + e.show);
			},
			toggle(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type)
			},
			clickCancel() {
				this[`showDialog`] = false;
				this.isEdit = false;
			},
			show(row) {
				// console.log(row)
				this.getTeamById(row.teamId);
				this.getEmployeeById(row.employeeId);
				this.salaryDetail.projectName = row.projectName;
				this.salaryDetail.addMinus = row.addMinus;
				this.salaryDetail.payment = row.payment;
				this.salaryDetail.payTime = row.payTime;
				this.salaryDetail.note = row.note;
				this.salaryDetail.pay = row.pay;
				this.getAddMinus(row.addMinus);
				this.getPayment(row.payment);
				this[`showDialog`] = true;
				this.isEdit = false;
			},
			edit(salary) {
				// console.log(salary)
				this.salaryData.id = salary.id;
				this.salaryData.employeeId = salary.employeeId;
				this.salaryData.pay = salary.pay;
				this.salaryData.teamId = salary.teamId;
				this.salaryData.projectId = salary.projectId;
				this.salaryData.addMinus = salary.addMinus;
				this.salaryData.payment = salary.payment;
				this.isEdit = true;
				this[`showDialog`] = true;
			},
			showDetail(row) {
				this.$dry.set("salary",row);
				uni.navigateTo({
					url: "salary-detail" 
				})
			},
			getAddMinus(addMinus) {
				this.addMinus.forEach(e => {
					if(e.value === addMinus) {
						this.salaryData.addMinusCN = e.text;
					}
				})
			},
			getPayment(payment) {
				this.payment.forEach(p => {
					if(p.value === payment) {
						this.salaryData.paymentCN = p.text;
					}
				})
			},
			getTeamById(teamId) {
				var token = this.$dry.getToken();
				if(token) {
					var data = this.$request.run("getTeamById", token);
					 uni.request({
					 	url: data.url,
						method: data.method,
						header: data.header,
						data: {
							"id": teamId
						},
						success: data => {
							if(data.statusCode === 200) {
								this.salaryDetail.team = data.data;
							}
						}
					 })
				}
			},
			getEmployeeById(employeeId) {
				var token = this.$dry.getToken();
				if(token) {
					var data = this.$request.run("getEmployeeById", token);
					 uni.request({
					 	url: data.url,
						method: data.method,
						header: data.header,
						data: {
							"id": employeeId
						},
						success: data => {
							if(data.statusCode === 200) {
								this.salaryDetail.employee = data.data;
							}
						}
					 })
				}
			},
			async getTeam() {
				var list = await this.$dry.getTeams(true);
				var team = [{
					text: '所有团队',
					value: ''
				}];
				list.forEach(e => {
					team.push({
						text: e.name,
						value: e.id
					})
				})
				this.team = team;
				
			},
			async getProjectsByCondition(e) {
				var projectList = this.$dry.get("project");
				var teamId = '';
				if(e) {
					teamId = e.detail.value[0].value;
				}
				var token = this.$dry.getToken();
				if (token) {
					projectList = await this.getProjects(teamId);
				}
				if(projectList.length != 0) {
					var newList = [{
						text: '所有项目',
						value: ''
					}];
					projectList.forEach(p => {
						newList.push({
							text: p.name,
							value: p.id,
						});
					});
					this.project = newList;
				}
				else{
					this.project = [];
				}
			},
			getProjects(teamId) {
				var token = this.$dry.getToken();
				var data = [];
				if (token) {
					data = this.$request.run("queryProjectsByCondition",token);
					return new Promise((resolve) => {
						uni.request({
							url: data.url,
							method: data.method,
							header: data.header,
							data: {
								"teamId": teamId,
								"queryAll": false
							},
							success: data => {
								resolve(data.data);
							}
						});
					});
				}
			},
			getEmployee() {
				var token = this.$dry.getToken();
				if(token){
					var data = this.$request.run("listEmployeeByConditions",token);
				    uni.request({
				    	url: data.url,
				    	method: data.method,
				    	header: data.header,
				    	data: {
							"projectId": this.filterValue.projectId,
							"employeeStatus": 'NORMAL'
						},
				    	success: data => {
				    		var worker = data.data;
							var newItems = [];
							if(worker.length != 0){
								worker.forEach(e => {
									newItems.push({
										text: e.realName == null || e.realName == '' ? e.nickName : e.realName,
										value: e.id
									});
								});
							}
							this.worker= newItems;
				    	},
				    	fail: (data, code) => {
				    		console.log('fail' + JSON.stringify(data));
				    	}
				    })
				}
			},
			getSalary() {
				var token = this.$dry.getToken();
				if(token){
					var data = [];
					if(this.detailOrTotal == 'TOTAL') {
						data = this.$request.run("queryAllSalaryByConditions",token);
					} else {
						data = this.$request.run("getSalaryByConditions",token);
					}
				    uni.request({
				    	url: data.url,
				    	method: data.method,
				    	header: data.header,
				    	data: this.filterValue,
						success: data => {
							if(data.statusCode === 200) {
								if(this.detailOrTotal == 'TOTAL') {
									this.tableData = data.data;
								} else {
									this.tableData = data.data.records;
									this.total = data.data.total;
								}
							}
							this.$refs.popup.close();
							// 清除时间选择 否则会相互影响查询结果
							this.dateRange = [];
							this.filterValue.startDate = '';
							this.filterValue.endDate = '';
						}
					});
				}	
			},
			submit() {
				if(this.isEdit == false) {
					this[`showDialog`] = false;
					return;
				}
				this.$refs['baseForm'].validate().then(res => {
					var token = this.$dry.getToken();
					if(token){
						var data = this.$request.run("updateSalary", token);
						uni.request({
							url: data.url,
							method: data.method,
							header: data.header,
							data: this.salaryData,
							success: data => {
								if(data.statusCode === 200) {
									uni.showToast({
										title: "操作成功！",
										duration: 1000
									});
									this.getSalary();
								}
							}
						})
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			changeTime(e){
				this.dateRange = e;
				this.filterValue.startDate = this.dateRange[0];
				this.filterValue.endDate = this.dateRange[1];
			},
		}
	}
</script>

<style lang="scss">
	.page-content {
		margin-top: 50px;
	}
	.data-chechbox-box {
		wight: 90%;
		height: 50px;
		padding: 0px 20px;
	}
	#submit-button {
		width: 50%;
		height: 100rpx;
		margin-bottom: -120rpx;
		margin-right: -30rpx;
		border: none;
		outline: none;
		z-index: 100;
	}
	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	@mixin height {
		/* #ifndef APP-NVUE */
		height: 100%;
		/* #endif */
		/* #ifdef APP-NVUE */
		flex: 1;
		/* #endif */
	}
	.popup-content {
		@include flex;
		align-items: center;
		justify-content: center;
		padding: 15px;
		height: auto;
		background-color: #fff;
	}
	.btn-view {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		padding: 15px;
		text-align: center;
		background-color: #fff;
		justify-content: center;
		align-items: center;
	}

	.topfixed-active{
	    width: 100%;
	    position: fixed;
	    top: var(--window-top);
	    left: 0;
	    background: #fff;
	    z-index: 9;
	    box-sizing: border-box;
	}
	.slot-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
	}
	.slot-title {
		flex: 1;
		width: 60px;
		font-size: 14px;
		color: #3b4144;
	}
	.slot-text {
		flex: 1;
		font-size: 12px;
		color: #999;
		margin-right: 10px;
	}
	.slot-image {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		margin-right: 10px;
		width: 30px;
		height: 30px;
	}

</style>
